<template>
  <div class="publish-form-container">
    <el-tabs v-model="activeType" @tab-click="handleTypeChange">
      <el-tab-pane label="寻物启事" name="lost">
        <div class="tab-description">
          <el-alert
            title="填写丢失物品的信息，帮助您尽快找回物品"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="失物招领" name="found">
        <div class="tab-description">
          <el-alert
            title="填写拾到物品的信息，帮助失主尽快找到物品"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="publish-form"
    >
      <el-form-item
        :label="activeType === 'lost' ? '丢失物品' : '拾到物品'"
        prop="name"
      >
        <el-input v-model="formData.name" placeholder="请输入物品名称" />
      </el-form-item>

      <el-form-item label="物品类别" prop="category">
        <el-select
          style="margin-right: 20px"
          v-model="formData.category"
          placeholder="请选择物品类别"
          @visible-change="handleSelectVisibleChange"
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        :label="activeType === 'lost' ? '丢失时间' : '拾获时间'"
        prop="time"
      >
        <el-date-picker
          v-model="formData.time"
          type="datetime"
          placeholder="选择日期时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
        />
      </el-form-item>

      <el-form-item
        :label="activeType === 'lost' ? '丢失地点' : '拾获地点'"
        prop="location"
      >
        <el-cascader
          style="margin-right: 20px"
          v-model="formData.location"
          :options="locationOptions"
          placeholder="请选择地点"
          clearable
        />
      </el-form-item>

      <el-form-item
        v-if="activeType === 'found'"
        label="保管地点"
        prop="keepLocation"
      >
        <el-input
          v-model="formData.keepLocation"
          placeholder="请输入物品当前保管地点"
        />
      </el-form-item>

      <el-form-item label="物品描述" prop="description" class="full-width">
        <el-input
          style="margin-right: 20px"
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述物品的特征、丢失/拾获的具体情况等"
        />
      </el-form-item>

      <el-form-item label="物品图片" prop="images" class="full-width">
        <el-upload
          class="upload-demo"
          action="https://example.com/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :limit="3"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleImageChange"
        >
          <template #default>
            <el-icon><Plus /></el-icon>
          </template>
          <template #file="{ file }">
            <div class="upload-item">
              <img :src="file.url" class="upload-image" />
              <div class="upload-actions">
                <el-icon @click.stop="handlePreview(file)"><ZoomIn /></el-icon>
                <el-icon @click.stop="handleRemove(file)"><Delete /></el-icon>
              </div>
            </div>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              请上传物品照片，每张不超过5MB，最多3张
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item v-if="activeType === 'lost'" label="悬赏金额" prop="reward">
        <el-input-number
          v-model="formData.reward"
          :min="0"
          :max="1000"
          :step="10"
          controls-position="right"
        />
        <span class="form-tip">元（可选）</span>
      </el-form-item>

      <el-form-item label="联系方式" prop="contact">
        <el-input
          style="margin-right: 20px"
          v-model="formData.contact"
          placeholder="联系方式（手机号/微信/QQ等）"
        />
      </el-form-item>

      <el-form-item v-if="activeType === 'lost'" label="隐私设置">
        <el-radio-group v-model="formData.privacy">
          <el-radio :label="1">公开联系方式</el-radio>
          <el-radio :label="0">仅平台可见</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="formData.agreement">
          我已阅读并同意
          <el-link type="primary" @click="showAgreement"
            >《平台使用协议》</el-link
          >
        </el-checkbox>
      </el-form-item>

      <div class="form-actions">
        <el-button @click="resetForm(formRef)">重置</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitForm(formRef)"
          :disabled="!formData.agreement"
        >
          提交
        </el-button>
      </div>
    </el-form>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewImage" alt="Preview Image" style="width: 100%" />
    </el-dialog>

    <!-- 协议对话框 -->
    <el-dialog v-model="agreementVisible" title="平台使用协议" width="50%">
      <div class="agreement-content">
        <h3>校园失物招领平台使用协议</h3>
        <p>1. 用户在本平台发布的信息应当真实、准确，不得发布虚假信息。</p>
        <p>2. 禁止发布与失物招领无关的信息，包括但不限于广告、营销等内容。</p>
        <p>3. 用户应当尊重他人隐私，不得在平台上发布他人的个人敏感信息。</p>
        <p>
          4.
          平台仅为失物招领信息的发布提供服务，物品认领过程中的纠纷由用户自行解决。
        </p>
        <p>5. 用户应当合理设置悬赏金额，不得以高额悬赏为噱头发布虚假信息。</p>
        <p>6. 平台有权对违反协议的用户进行警告、删除信息或封禁账号等处理。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="agreementVisible = false">关闭</el-button>
          <el-button type="primary" @click="agreeTerms"> 同意并继续 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交成功对话框 -->
    <el-dialog v-model="successVisible" title="提交成功" width="30%">
      <div class="success-message">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <p>
          您的{{ activeType === "lost" ? "寻物启事" : "招领信息" }}已提交成功！
        </p>
        <p>信息编号：{{ submittedId }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="goToList">查看列表</el-button>
          <el-button type="primary" @click="continueSubmit">
            继续发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, ZoomIn, Delete, CircleCheck } from "@element-plus/icons-vue";
import api from "@/utils/api";

export default {
  name: "PublishForm",
  components: {
    Plus,
    ZoomIn,
    Delete,
    CircleCheck,
  },
  setup() {
    // 表单引用
    const formRef = ref(null);
    const route = useRoute();
    const router = useRouter();

    //代表当前是寻物启事还是失物招领
    const activeType = ref("lost");

    // 表单数据
    const formData = reactive({
      name: "",
      category: "",
      time: "",
      location: [],
      keepLocation: "",
      description: "",
      images: [],
      contact: "",
      reward: 0,
      privacy: 1,
      agreement: false,
    });

    // 将静态分类数据改为响应式数据
    const categories = ref([]);

    // 添加一个标记变量来跟踪组件是否已卸载
    const isComponentMounted = ref(true);

    // 将原来的固定locationOptions改为响应式数据
    const locationOptions = ref([]);

    // 添加获取分类的方法
    const fetchCategories = async () => {
      try {
        const response = await api.get("/categories");
        if (response.data.code === 200) {
          categories.value = response.data.data;
        } else {
          ElMessage.error("获取分类数据失败");
        }
      } catch (error) {
        console.error("获取分类失败", error);
        categories.value = [];
      }
    };

    // 在组件挂载时获取地点数据
    onMounted(() => {
      isComponentMounted.value = true;
      console.log("组件已挂载，开始初始化...");
      // 根据路由参数设置表单类型
      if (route.query.type === "found") {
        activeType.value = "found";
      }

      // 组件挂载后获取分类和地点数据
      fetchCategories();
      fetchLocations();
    });

    // 获取地点的方法
    const fetchLocations = async () => {
      try {
        const response = await api.get("/locations");
        if (response.data.code === 200) {
          locationOptions.value = response.data.data;
        } else {
          ElMessage.error("获取地点数据失败");
        }
      } catch (error) {
        console.error("获取地点失败", error);
        locationOptions.value = [];
      }
    };

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: "请输入物品名称", trigger: "blur" },
        { min: 2, max: 20, message: "长度在2到20个字符", trigger: "blur" },
      ],
      category: [
        { required: true, message: "请选择物品类别", trigger: "change" },
      ],
      time: [{ required: true, message: "请选择时间", trigger: "change" }],
      location: [{ required: true, message: "请选择地点", trigger: "change" }],
      keepLocation: [
        { required: true, message: "请输入保管地点", trigger: "blur" },
      ],
      description: [
        { required: true, message: "请输入物品描述", trigger: "blur" },
        { min: 10, max: 500, message: "长度在10到500个字符", trigger: "blur" },
      ],
      contact: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
    };

    // 状态变量
    const submitting = ref(false);
    const previewVisible = ref(false);
    const previewImage = ref("");
    const agreementVisible = ref(false);
    const successVisible = ref(false);
    const submittedId = ref("");

    // 监听表单类型变化
    watch(activeType, () => {
      // 切换表单类型时重置表单
      resetForm(formRef.value);
    });

    // 方法
    const handleTypeChange = (tab) => {
      activeType.value = tab.props.name;
    };

    const handlePreview = (file) => {
      previewImage.value = file.url;
      previewVisible.value = true;
    };

    const handleRemove = (file) => {
      const fileList = formData.images;
      const index = fileList.findIndex((item) => item.uid === file.uid);
      if (index !== -1) {
        fileList.splice(index, 1);
      }
    };

    const beforeUpload = (file) => {
      const isImage = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        ElMessage.error("只能上传图片文件!");
        return false;
      }
      if (!isLt5M) {
        ElMessage.error("图片大小不能超过5MB!");
        return false;
      }
      return true;
    };

    const handleImageChange = (file, fileList) => {
      formData.images = fileList;
    };

    const showAgreement = () => {
      agreementVisible.value = true;
    };

    const agreeTerms = () => {
      formData.agreement = true;
      agreementVisible.value = false;
    };

    const submitForm = async (formEl) => {
      if (!formEl) return;

      await formEl.validate(async (valid) => {
        if (valid) {
          submitting.value = true;

          try {
            // 准备提交数据
            const submitData = {
              type: activeType.value,
              name: formData.name,
              category: formData.category,
              time: formData.time,
              location: formData.location,
              description: formData.description,
              contact: formData.contact,
              privacy: formData.privacy,
            };

            // 根据类型添加特定字段
            if (activeType.value === "lost") {
              submitData.reward = formData.reward;
            } else if (activeType.value === "found") {
              submitData.keepLocation = formData.keepLocation;
            }

            // 处理图片数据
            if (formData.images && formData.images.length > 0) {
              submitData.images = await Promise.all(
                formData.images.map(async (file) => {
                  // 将文件转为Base64编码
                  return await fileToBase64(file.raw);
                })
              );
            }

            // 发送API请求
            const response = await api.post("/items", submitData);

            if (response.data.code === 200) {
              submitting.value = false;
              submittedId.value = response.data.data.id;
              successVisible.value = true;
              ElMessage.success("信息提交成功");
            } else {
              throw new Error(response.data.message || "提交失败");
            }
          } catch (error) {
            submitting.value = false;
            ElMessage.error(`提交失败: ${error.message}`);
            console.error("提交表单出错:", error);
          }
        } else {
          ElMessage.error("请完善表单信息");
        }
      });
    };

    // 辅助函数：将文件转为Base64
    const fileToBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result.split(",")[1]); // 移除data:image/jpeg;base64,前缀
        reader.onerror = (error) => reject(error);
      });
    };

    const resetForm = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
      formData.images = [];
      formData.reward = 0;
      formData.privacy = 1;
      formData.agreement = false;
    };

    const goToList = () => {
      successVisible.value = false;
      router.push(activeType.value === "lost" ? "/lost" : "/found");
    };

    const continueSubmit = () => {
      successVisible.value = false;
      resetForm(formRef.value);
    };

    const handleSelectVisibleChange = (visible) => {
      if (visible && categories.value.length === 0) {
        fetchCategories().catch((err) => console.error("加载分类失败", err));
      }
    };

    return {
      formRef,
      activeType,
      formData,
      categories,
      locationOptions,
      formRules,
      submitting,
      previewVisible,
      previewImage,
      agreementVisible,
      successVisible,
      submittedId,
      handleTypeChange,
      handlePreview,
      handleRemove,
      beforeUpload,
      handleImageChange,
      showAgreement,
      agreeTerms,
      submitForm,
      resetForm,
      goToList,
      continueSubmit,
      fetchCategories,
      handleSelectVisibleChange,
      fetchLocations,
    };
  },
};
</script>

<style scoped>
.publish-form-container {
  width: 100%;
  padding: 20px;
}

.tab-description {
  margin-bottom: 20px;
}

.publish-form {
  margin-top: 20px;
  width: 100%;
}

/* 调整表单布局，使用两列布局更好利用宽度 */
:deep(.el-form) {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 20px;
}

/* 让某些表单项占满整行 */
:deep(.el-form-item.full-width) {
  grid-column: span 2;
}

/* 必须先将所有表单项设为全宽，再单独设置特殊项 */
:deep(.el-form-item) {
  margin-bottom: 22px;
  width: 100%;
}

:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-cascader),
:deep(.el-date-picker),
:deep(.el-textarea) {
  width: 100%;
}

/* 特殊处理文本域和上传控件等需要全宽的元素 */
:deep(.el-form-item.el-form-item--feedback) {
  grid-column: span 2;
}

.form-actions {
  grid-column: span 2;
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.form-tip {
  margin-left: 10px;
  color: var(--text-secondary);
}

.upload-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-actions {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  gap: 5px;
  padding: 5px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 0 0 5px;
}

.upload-actions .el-icon {
  color: white;
  cursor: pointer;
  font-size: 16px;
  padding: 2px;
}

.agreement-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 0 10px;
}

.agreement-content h3 {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-content p {
  margin-bottom: 10px;
  line-height: 1.5;
}

.success-message {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 20px;
}

.success-message p {
  margin: 10px 0;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 